package viroyal.com.base.activity.splash;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.aiwinn.base.util.AppUtils;
import com.amap.api.location.AMapLocationListener;
import com.baidu.tts.BaiDuTtsUtil;
import com.suntiago.baseui.activity.base.theMvp.databind.DataBinder;
import com.suntiago.baseui.utils.NetUtils;
import com.suntiago.baseui.utils.SPUtils;
import com.suntiago.baseui.utils.ToastUtils;
import com.suntiago.baseui.utils.log.Slog;
import com.suntiago.getpermission.rxpermissions.RxPermissions;
import com.suntiago.network.network.ErrorCode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import viroyal.com.base.AppConfig;
import viroyal.com.base.MyApp;
import viroyal.com.base.activity.main.MainActivity;
import viroyal.com.base.common.ConstantsYJ;
import viroyal.com.base.face.aiwinn.AiwinnManager;
import viroyal.com.base.model.IOTModel;
import viroyal.com.base.net.req.RegisterIOTRequest;
import viroyal.com.base.net.req.TokenRequest;
import viroyal.com.base.net.rsp.TokenResponseS;
import viroyal.com.base.util.DeviceInfoUtil;
import viroyal.com.base.util.Utils;
import viroyal.com.dev.NFCMonitorBaseActivity;
import viroyal.com.dev.splash.ConfigDevice;

/**
 * Created by zy on 2018/12/6.
 */

public class SplashIp extends NFCMonitorBaseActivity<SplashAppDelegate, SplashModel> {
  /**
   * 声明定位回调监听器
   */
//  public AMapLocationListener mLocationListener = aMapLocation -> {
//    if (aMapLocation != null) {
//      if (aMapLocation.getErrorCode() == 0) {
//        //获取三天的天气
//        ConstantsYJ.LOCATION_ADDRESS = aMapLocation.getCity();
//        Slog.e(TAG, "aMapLocation.getCity(): " + aMapLocation.getCity());
//      } else {
//        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//        Slog.e(TAG, "[AMapLocation]" + aMapLocation + "----> location Error, ErrCode:"
//            + aMapLocation.getErrorCode() + ", errInfo:"
//            + aMapLocation.getErrorInfo());
//      }
//    }
//  };
    private Timer timer;
  private String access_token="";

  private void initPermission() {
    RxPermissions.getInstance(this).request(
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.INTERNET,
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.RECEIVE_BOOT_COMPLETED,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_WIFI_STATE,
        Manifest.permission.CHANGE_WIFI_STATE,
        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
        Manifest.permission.READ_PHONE_STATE)
        .subscribe(aBoolean -> {
          Slog.d(TAG, "requestPermissionAndEnterApp  []:" + aBoolean);
          if (!aBoolean) {
            viewDelegate.showToast("请手动打开权限！");
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
          } else {
            Slog.d(TAG, "initPermission: getNumberOfCameras()=" + Camera.getNumberOfCameras());

            /**
             * 先获取物联网token
             */
//            IOTModel.get().getToken(tokenResponseS -> {
//              if (tokenResponseS.error_code == 0) {
//                SPUtils.getInstance(SplashIp.this).put(AppConfig.ACCESS_TOKEN, tokenResponseS.data.getAccess_token());
//                access_token = tokenResponseS.data.getAccess_token();
                //适配非触摸版班牌
//                if (Camera.getNumberOfCameras() != 0) {
//                  MyApp.initAiwinnFace(() -> {
//                    //初始化完成进行自注册
//                    String isRegister = SPUtils.getInstance(SplashIp.this).get("device_is_register");
//                    if (!TextUtils.isEmpty(isRegister) && "1".equals(isRegister)) {
//                      //已经注册了
//                      SplashIp.this.skipActivity();
//                    } else {
//                      //还未注册
//                      new Thread(SplashIp.this::deviceRegister).start();
//                    }
//                  });
//                } else {
                  //初始化完成进行自注册
                  String isRegister = SPUtils.getInstance(SplashIp.this).get("device_is_register");
                  if (!TextUtils.isEmpty(isRegister) && "1".equals(isRegister)) {
                    //已经注册了
                    SplashIp.this.skipActivity();
                  } else {
                    //还未注册
                    new Thread(SplashIp.this::deviceRegister).start();
                  }
//                }
//              }
//            });
            MyApp.initBaiDuTts();
//            MyApp.initAMap(mLocationListener);
          }
        });
  }

  /**
   * 设备自注册
   */
  private void deviceRegister() {
    String deviceId = ConfigDevice.getDeviceId();
    //注册物联网
//    addRxSubscription(iModel.deviceRegister_iot(access_token,new RegisterIOTRequest("电子班牌",DeviceInfoUtil.getInstance(SplashIp.this).getMac(),deviceId,"1.0"), viewDelegate, regidterIOTResponseS->{
//      if (regidterIOTResponseS.error_code == 0 || regidterIOTResponseS.error_code == 1010) {
//        SPUtils.getInstance(SplashIp.this).put(AppConfig.DEVICE_ID, regidterIOTResponseS.data.device_id);
        addRxSubscription(iModel.deviceRegister(deviceId, viewDelegate, deviceRegidterResponseS -> {
          if (deviceRegidterResponseS.error_code == ErrorCode.SUCCESS) {
            //注册成功
            SPUtils.getInstance(SplashIp.this).put("device_is_register", "1");
            skipActivity();
          } else if (deviceRegidterResponseS.error_code == 0) {
            SPUtils.getInstance(SplashIp.this).put("device_is_register", "1");
            skipActivity();
          } else {
            ToastUtils.showToast(this, deviceRegidterResponseS.error_msg);
          }
        }));
//      } else {
//        ToastUtils.showToast(this, regidterIOTResponseS.error_msg);
//      }
//    }));
  }

  private void skipActivity() {
    addRxSubscription(iModel.getSchoolId(ConfigDevice.getDeviceId(), getSchoolIdResponseS -> {
      //有时候会出现school_id为空的情况 这里重新判断
      if (getSchoolIdResponseS.error_code == ErrorCode.SUCCESS) {
        SPUtils.getInstance(SplashIp.this).put(AppConfig.SCHOOL_ID, getSchoolIdResponseS.extra.unit_id);
      }
      ConfigDevice.school_id = SPUtils.getInstance(SplashIp.this).get(AppConfig.SCHOOL_ID, "1000");
      if (NetUtils.isConnected(this)) {
        addRxSubscription(iModel.getDeviceInfo(viewDelegate, sdkAlertDialog,this, SplashIp.this, rsp -> {
          dismissDialog();
            timer.cancel();
          finish();
          startActivity(new Intent(SplashIp.this, MainActivity.class));
        }));
      } else {
        dismissDialog();
          timer.cancel();
        finish();
        startActivity(new Intent(SplashIp.this, MainActivity.class));
      }

    }));
  }

  private AlertDialog sdkAlertDialog;

  private void showAlertDialog() {
    sdkAlertDialog = new AlertDialog.Builder(this)
        .setTitle("SDK配置初始化")
        .setCancelable(false)
        .setMessage("正在初始化SDK配置...")
        .create();
    sdkAlertDialog.setOnKeyListener((dialog, keyCode, event) -> {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
        AiwinnManager.get().release();
        BaiDuTtsUtil.release();
        AppUtils.exitApp();
      }
      return false;
    });
    if(!sdkAlertDialog.isShowing()) {
      sdkAlertDialog.show();
      //放在show()之后，不然有些属性是没有效果的，比如height和width
      Window dialogWindow = sdkAlertDialog.getWindow();
      WindowManager m = getWindowManager();
      Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
      WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
      // 设置宽度
      p.gravity = Gravity.CENTER;//设置位置
      dialogWindow.setAttributes(p);
    }
  }

  private void dismissDialog() {
    if (null != sdkAlertDialog) {
      sdkAlertDialog.dismiss();
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    showAlertDialog();
    //配置加载完成初始化百度语音、高德地图、人脸sdk
    initPermission();
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //将设备的uuid写入到本地viroyal_mac.txt中
    String path = Environment.getExternalStorageDirectory() + File.separator + "viroyal_mac.txt";
    File file = new File(path);
    if (!file.exists()) {
      try {
        file.createNewFile();
        FileOutputStream out = new FileOutputStream(file);
        out.write(DeviceInfoUtil.getInstance(this).getDeviceUuid().getBytes("UTF-8"));
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

      timer = new Timer();
      timer.schedule(new TimerTask() {
          @Override
          public void run() {
              timer.cancel();
              PackageManager mPackageManager = getPackageManager();
              Intent intent = mPackageManager.getLaunchIntentForPackage(getPackageName());
              intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              startActivity(intent);
              android.os.Process.killProcess(android.os.Process.myPid());
          }
      }, 60 * 1000);
  }

  @Override
  protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
  }

  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Utils.fullScreen(getWindow());
  }

  @Override
  protected NFCSwitch NFCSwitch() {
    return NFCSwitch.DEFAULT;
  }

  @Override
  public DataBinder getDataBinder() {
    return super.getDataBinder();
  }

  @Override
  protected Class<SplashAppDelegate> getDelegateClass() {
    return SplashAppDelegate.class;
  }

  @Override
  protected Class<SplashModel> getModelClass() {
    return SplashModel.class;
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
  }
}
